import { create } from 'zustand';

interface AudioState {
  audio: HTMLAudioElement | null;
  isPlaying: boolean;
  currentTime: number;
}

interface AudioStore extends AudioState {
  setAudio: (audio: HTMLAudioElement | null) => void;
  setIsPlaying: (isPlaying: boolean) => void;
  setCurrentTime: (time: number) => void;
  stopCurrentAudio: () => void;
}

export const useAudioStore = create<AudioStore>((set, get) => ({
  audio: null,
  isPlaying: false,
  currentTime: 0,
  setAudio: (audio) => set({ audio }),
  setIsPlaying: (isPlaying) => set({ isPlaying }),
  setCurrentTime: (time) => set({ currentTime: time }),
  stopCurrentAudio: () => {
    const { audio } = get();
    if (audio) {
      audio.pause();
      audio.currentTime = 0;
      set({ isPlaying: false, currentTime: 0 });
    }
  },
}));

export class AudioService {
  static async playAudio(url: string): Promise<HTMLAudioElement> {
    const { audio: currentAudio, setAudio, setIsPlaying, setCurrentTime } = useAudioStore.getState();

    if (currentAudio) {
      currentAudio.pause();
      currentAudio.currentTime = 0;
    }

    const audio = new Audio(url);
    
    audio.addEventListener('timeupdate', () => {
      setCurrentTime(audio.currentTime);
    });

    audio.addEventListener('ended', () => {
      setIsPlaying(false);
      setCurrentTime(0);
    });

    setAudio(audio);
    setIsPlaying(true);
    await audio.play();

    return audio;
  }

  static async toggleAudio(): Promise<void> {
    const { audio, isPlaying, currentTime, setIsPlaying } = useAudioStore.getState();

    if (!audio) return;

    if (isPlaying) {
      audio.pause();
      setIsPlaying(false);
    } else {
      audio.currentTime = currentTime;
      await audio.play();
      setIsPlaying(true);
    }
  }
}